|
|
|
|
|
|
|
What happens when you run this program? First, the operating system loads the program into memory. Space is allocated for the code, for any global data, and for the application's stack. The system then transfers control to the starting point of the program, which performs some internal initialization and then calls Sub Main(). |
|
|
|
|
|
|
|
|
Figure T4-2a:
The process stack on initialization |
|
|
|
|
|
|
|
|
The top of the stack at this point contains a return address. What is a return address? Every time you call a function, the CPU jumps to run the code belonging to that function. When you exit the function, the processor needs a way to figure out where it came from in order to go back and run the instruction that follows the function call. The address of that instruction is the return address, which is stored on the stack when a function is called. You can see this in Figure T4-2a. When Sub Main() is called, the return address points back to a location in the application that handles initialization and cleanup and ultimately returns control to the operating system when the program terminates. |
|
|
|
|
|
|
|
|
Figure T4-2b shows what happens when Function B() is called during Sub Main(). The address of the location in Sub Main() after the function call is stored on the stack, and execution continues at the beginning of Function B(). The same process occurs when Function A() is called from Function B(), as shown in Figure T4-2c. |
|
|
|
|
|
|
|
|
Figures T4-2b, T4-2c:
Return addresses are pushed to the stack as functions are called |
|
|
|
|
|
|
|
|
When Function A() finishes executing, the return value is popped off the top of the stack, and execution continues in Function B(), as shown in Figure T4-2d. |
|
|
|
|
|